//
//  MainViewController.swift
//  Swift2048
//
//  Created by LiynXu on 2016/9/27.
//  Copyright © 2016年 LiynXu. All rights reserved.
//

import UIKit

class MainViewController: UIViewController {
    
    var score:Int?{
        didSet{
            if let _score = score{
                scoreLabel.text = "分数:\(_score)"
            }else{
                scoreLabel.text = "分数:\(0)"
            }
            
        }
    }
    
    var maxScore:Int{
        
        return userModel.maxScore
    }
    
    var dimension:Int{
        return userModel.matrix
    }
    
    let scoreLabel:UILabel = {
        let label = UILabel.init(frame: CGRectMake(0, 0, 80, 30))
        label.backgroundColor = UIColor.brownColor()
        return label
    }()
    
    let maxScoreLabel:UILabel = {
        let label = UILabel.init(frame: CGRectMake(0, 0, 80, 30))
        label.backgroundColor = UIColor.brownColor()
        return label
    }()
    
    let baseView = UIView(frame: CGRectMake(0, 64, screenWidth, screenHeight-108))
    
    let metrixView = UIView()
    
    let metrixSpace:CGFloat = 6
    
    let metrixWidth:CGFloat = 50
    
    var numbers:Array = Array<Int>()
    
    var labels:Array = Array<NumberLabel>()
    
    var gameModel:GameModel = GameModel()
    
    override func viewDidLoad() {
        
        super.viewDidLoad()
        gameModel.addObserver(self, forKeyPath: "gameModel.dimension", options: .New, context: nil)
       
        self.view.addSubview(baseView)
        setupMetrix(dimension: self.dimension)
        initGame()
        setupScoreView()
        setupButtons()
        addGestureRecognizer()
        self.gameModel.dimension = 5
        
        //self.gameModel.setValue(3, forKey: "dimension")
        
        gameModel.setValuesForKeysWithDictionary(["dimension":5])
        
    }
    override func observeValueForKeyPath(keyPath: String?, ofObject object: AnyObject?, change: [String : AnyObject]?, context: UnsafeMutablePointer<Void>) {
        print(keyPath!+"\(object!)"+"\(change!)")
    }
    
    func setupScoreView()  {
        let margin = (screenWidth-160)/3.0
        self.scoreLabel.center = CGPointMake(margin+40, 40)
        self.maxScoreLabel.center = CGPointMake(margin+margin+120, 40)
        baseView.addSubview(scoreLabel)
        baseView.addSubview(maxScoreLabel)
    }
    
    func setupMetrix(dimension dimension:Int)  {
        let width = CGFloat(dimension)*metrixWidth+(CGFloat(dimension)-1)*metrixSpace
        self.metrixView.frame = CGRectMake((screenWidth-width)/2.0, 90, width, width)
        baseView.addSubview(metrixView)
        metrixView.backgroundColor = UIColor.clearColor()
        
        for i in 0..<dimension {
            let y = (metrixWidth+metrixSpace)*CGFloat(i)
            for j in 0..<dimension {
                let x = (metrixWidth+metrixSpace)*CGFloat(j)
                let rect = CGRectMake(x, y, metrixWidth, metrixWidth)
                let label = NumberLabel(frame: rect)
                label.textAlignment = NSTextAlignment.Center
                label.font = UIFont.systemFontOfSize(30)
                label.value = 0
                
                label.textColor = UIColor.whiteColor()
                
                metrixView.addSubview(label)
                
                labels.append(label)
                
            }
        }
        
    }
    
    func initGame() {
        score = 0
        for i in 0..<(dimension*dimension) {
            labels[i].value = 0
        }
        
        let num1 = Int(arc4random())%(dimension*dimension)
        var num2 = Int(arc4random())%(dimension*dimension)
        while num2==num1 {
            num2 = Int(arc4random())%(dimension*dimension)
        }
        
        labels[num1].value = 2
        labels[num2].value = 2
        
        
    }
    func setupButtons() {
        
        let maxY = CGRectGetMaxY(baseView.frame)-80
        
        let resetButton = UIButton(type: .Custom)
        resetButton.frame = CGRectMake(0, 0, 70, 40)
        resetButton.center = CGPointMake((screenWidth - 140)/3.0+35,maxY - 70)
        
        resetButton.backgroundColor = UIColor.brownColor()
        resetButton.setTitle("重置", forState: .Normal)
        resetButton.setTitleColor(UIColor.blackColor(), forState: .Normal)
        resetButton.addTarget(self, action: #selector(MainViewController.resetMetrix), forControlEvents: .TouchUpInside)
        
        let newNumButton = UIButton(type: .Custom)
        newNumButton.frame = CGRectMake(0, 0, 70, 40)
        newNumButton.center = CGPointMake((screenWidth - 140)/3.0*2+35+70,maxY - 70)
        
        newNumButton.backgroundColor = UIColor.brownColor()
        newNumButton.setTitle("新数", forState: .Normal)
        newNumButton.addTarget(self, action: #selector(MainViewController.newNum), forControlEvents: .TouchUpInside)
        newNumButton.setTitleColor(UIColor.blackColor(), forState: .Normal)
        
        baseView.addSubview(resetButton)
        baseView.addSubview(newNumButton)
    }
    
    func resetMetrix()  {
        
        initGame()
        score = 0
        
    }
    
    func newNum()  {
        let label = labels[Int(arc4random())%(dimension*dimension)]
        label.value = 2
        
    }
    
    func addGestureRecognizer() {
        let swipeUp = UISwipeGestureRecognizer(target: self, action: #selector(MainViewController.upAction))
        swipeUp.direction = .Up
        
        let swipeDown = UISwipeGestureRecognizer(target: self, action: #selector(MainViewController.downAction))
        swipeDown.direction = .Down
        
        let swipeLeft = UISwipeGestureRecognizer(target: self, action: #selector(MainViewController.leftAction))
        swipeLeft.direction = .Left
        
        let swipeRight = UISwipeGestureRecognizer(target: self, action: #selector(MainViewController.rightAction))
        swipeRight.direction = .Right
        
        baseView.addGestureRecognizer(swipeUp)
        baseView.addGestureRecognizer(swipeDown)
        baseView.addGestureRecognizer(swipeLeft)
        baseView.addGestureRecognizer(swipeRight)
        
    }
    
    func upAction()  {
        print("UP")
        
        
        
        
    }
    func downAction()  {
        print("Down")
    }
    func leftAction()  {
        print("Left")
    }
    func rightAction()  {
        print("Right")
    }
    
}
